package lq.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import lq.common.entity.StudyConstant;
import lq.common.entity.StudyResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;

/**
 * 全局拦截器
 * 拦截所有请求,验证是否包含zuul过滤器包含的zuul token
 * 这个拦截器会在几乎所有的微服务中使用
 *
 * 实现HandlerInterceptor 的 preHandle方法,可以拦截所有的Web请求
 */
public class StudyServerProtectInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader(StudyConstant.ZUUL_TOKEN_HEADER);
        String zuulToken = new String(Base64Utils.encode(StudyConstant.ZUUL_TOKEN_VALUE.getBytes()));
        // 校验zuul token的正确性
        if (StringUtils.equals(zuulToken, token)) {
            return true;
        } else {
            StudyResponse studyResponse = new StudyResponse();
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write(JSONObject.toJSONString(studyResponse.message("请通过网关获取资源")));
            return false;
        }
    }
}
